/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.freemarker;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;

/**
 * @author: libo Date: 17-3-1 Time: 上午11:59
 * @version: \$Id$
 */
public class FreemarkerSupports {

    /**
     * block节点名称前缀
     */
    public static String BLOCK_PRE = "__ftl_override__";
    /**
     * 当前override节点
     */
    public static String OVERRIDE_CURRENT_NODE = "__ftl_override_current_node";

    public static String getOverrideVariableName(String name) {
        return BLOCK_PRE + name;
    }

    public static String getRequiredArgument(Map params, String key) throws TemplateException {
        Object value = params.get(key);
        if (value == null || StringUtils.isEmpty(value.toString())) {
            throw new TemplateModelException("not found required parameter:" + key + " for directive");
        }
        return value.toString();
    }

    public static OverrideBodyWrapper getOverrideBody(Environment env, String name) throws TemplateModelException {
        return (OverrideBodyWrapper) env.getVariable(getOverrideVariableName(name));
    }

    public static void setParentForTop(OverrideBodyWrapper topBody, OverrideBodyWrapper overrideBody) {
        OverrideBodyWrapper parent = overrideBody;
        while (parent.getParentBody() != null) {
            parent = parent.getParentBody();
        }
        parent.setParentBody(topBody);
    }
}
